require('dotenv').config()
// 导入数据库操作模块
const db = require('../../db')
// 导入 bcryptjs 这个包
const bcrypt = require('bcryptjs')
// 导入生成 Token 的包
const jwt = require('jsonwebtoken')

// 登录
// MARK POST / sys / login	登录
exports.login = (req, res) => {
  const { mobile, password } = req.body

  // 验证输入数据
  if (!mobile || !password) {
    return res.status(400).json({ success: false, code: 10001, message: '手机号和密码不能为空' })
  }

  // 查询用户信息
  const query = 'SELECT * FROM user WHERE mobile = ?'
  db.query(query, [mobile], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10002, message: '查询用户失败', error: err.message })
    }

    if (results.length === 0) {
      return res.status(400).json({ success: false, code: 10003, message: '手机号或密码错误' })
    }

    const user = results[0]

    // 验证密码
    bcrypt.compare(password, user.password, (err, isMatch) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10004, message: '密码验证失败', error: err.message })
      }

      if (!isMatch) {
        return res.status(400).json({ success: false, code: 10005, message: '手机号或密码错误' })
      }

      // 生成 JWT 令牌 // MARK 存储id以及mobile
      const token = jwt.sign(
        { id: user.id, mobile: user.mobile },
        process.env.JWT_SECRET,
        { expiresIn: process.env.JWT_EXPIRES_IN }
      )

      res.json({
        success: true,
        code: 10000,
        data: { token },
        message: '登录成功'
      })
    })
  })
}
// 用户相关
// MARK GET / sys / profile	获取用户基本资料
exports.profile = (req, res) => {
  // 从 token 中获取 id
  const id = req.user.id // 假设 token 中的 id 已经解析并存储在 req.user.id 中
  console.log("req.user.id >>>" + id)
  // 查询 employee 表中的信息
  const employeeQuery = `
    SELECT id, mobile, username, staffPhoto, departmentId, companyId, roleId
    FROM employee
    WHERE id = ?
  `
  db.query(employeeQuery, [id], (err, employeeResults) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10002, message: '查询员工信息失败', error: err.message })
    }

    if (employeeResults.length === 0) {
      return res.status(400).json({ success: false, code: 10003, message: '员工信息不存在' })
    }

    const employee = employeeResults[0]

    // 查询 department 表中的 name
    const departmentQuery = `
      SELECT name AS departmentName
      FROM department
      WHERE id = ?
    `
    db.query(departmentQuery, [employee.departmentId], (err, departmentResults) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10002, message: '查询部门信息失败', error: err.message })
      }

      const departmentName = departmentResults.length > 0 ? departmentResults[0].departmentName : ''

      // 查询 company 表中的 name
      const companyQuery = `
        SELECT name AS companyName
        FROM company
        WHERE id = ?
      `
      db.query(companyQuery, [employee.companyId], (err, companyResults) => {
        if (err) {
          return res.status(500).json({ success: false, code: 10002, message: '查询公司信息失败', error: err.message })
        }

        const companyName = companyResults.length > 0 ? companyResults[0].companyName : ''

        // 查询 role 表中的 permIds
        const roleQuery = `
          SELECT permIds
          FROM role
          WHERE id = ?
        `
        db.query(roleQuery, [employee.roleId], (err, roleResults) => {
          if (err) {
            return res.status(500).json({ success: false, code: 10002, message: '查询角色信息失败', error: err.message })
          }

          if (roleResults.length === 0) {
            return res.status(400).json({ success: false, code: 10003, message: '角色信息不存在' })
          }

          const permIds = roleResults[0].permIds.split('、')

          // 查询 permission 表中的数据
          const permissionQuery = `
            SELECT id, code, type
            FROM permission
            WHERE id IN (${permIds.map(() => '?').join(', ')})
          `
          db.query(permissionQuery, permIds, (err, permissionResults) => {
            if (err) {
              return res.status(500).json({ success: false, code: 10002, message: '查询权限信息失败', error: err.message })
            }

            const perms = permissionResults
            console.log("perms >>> ", perms)
            // 声明 roles 变量
            const roles = { menus: [], points: [] }

            // 将 perms 中 type 为 1 的 code 合成一个列表
            roles.menus = perms.filter(p => p.type === 1).map(p => p.code)

            // 将 perms 中 type 为 2 的 code 合成一个列表
            roles.points = perms.filter(p => p.type === 2).map(p => p.code)

            // 返回数据
            res.json({
              success: true,
              code: 10000,
              data: {
                roles,
                companyId: employee.companyId,
                company: companyName,
                userId: employee.id,
                mobile: employee.mobile,
                username: employee.username,
                staffPhoto: employee.staffPhoto,
                departmentName,
                departmentId: employee.departmentId,
              },
              message: '获取资料成功'
            })
          })
        })
      })
    })
  })
}
// 注册
// MARK POST / sys / register	注册
exports.register = (req, res) => {
  const { mobile, password } = req.body

  // 验证输入数据
  if (!mobile || !password) {
    return res.status(400).json({ success: false, code: 10001, message: '手机号和密码不能为空' })
  }

  // 查询用户信息
  const query = 'SELECT * FROM user WHERE mobile = ?'
  db.query(query, [mobile], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10002, message: '查询用户失败', error: err.message })
    }

    if (results.length > 0) {
      return res.status(400).json({ success: false, code: 10006, message: '手机号已存在' })
    }

    // 加密密码
    bcrypt.hash(password, 10, (err, hashedPassword) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10007, message: '密码加密失败', error: err.message })
      }

      // 插入新用户
      const insertQuery = 'INSERT INTO user (mobile, password) VALUES (?, ?)'
      db.query(insertQuery, [mobile, hashedPassword], (err, insertResult) => {
        if (err) {
          return res.status(500).json({ success: false, code: 10008, message: '注册用户失败', error: err.message })
        }

        res.json({
          success: true,
          code: 10000,
          message: '注册成功'
        })
      })
    })
  })
}
